package com.yunxi.service.app.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunxi.core.base.Constant;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.eai.pojo.app.pojo.*;
import com.yunxi.eai.pojo.esb.EsbVO;
import com.yunxi.eai.service.app.AppService;
import com.yunxi.hubToBaseData.pojo.*;
import com.yunxi.hubToBaseData.service.App2BaseDataService;
import com.yunxi.hubToBaseData.service.AppCustomerCredit2PMS;
import com.yunxi.hubToBiz.pojo.CancelVOAPP;
import com.yunxi.hubToBiz.pojo.CustomerTestDriveVO;
import com.yunxi.hubToBiz.pojo.OrderCustomerVO;
import com.yunxi.hubToBiz.service.App2PmsDubboService;
import com.yunxi.hubToBiz.service.NewCustomerClueService;
import com.yunxi.hubToBiz.service.ProduceModelCheckDubboService;
import com.yunxi.model.eai.EaiLog;
import com.yunxi.rocketmq.producer.EaiLogsProducer;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/6/1.
 */
@Service
@Qualifier("appServiceImpl")
public class AppServiceImpl implements AppService {
    private static final Logger logger = LoggerFactory.getLogger(AppServiceImpl.class);

    @Autowired
    private EaiLogsProducer eaiLogsProducer;
    @Autowired
    private App2PmsDubboService app2PmsImpl;
    @Autowired
    private App2BaseDataService app2BaseDataServiceImpl;
    @Autowired
    private NewCustomerClueService newCustomerClueServiceImpl;
    @Autowired
    private Mapper dozerMapper;
    @Autowired
    private ProduceModelCheckDubboService produceModelCheckDubboServiceImpl;
    @Autowired
    private AppCustomerCredit2PMS appCustomerCredit2PMSImpl;

    @Override
    public ApiResult distributeApp(EsbVO esbVO) {
        String serviceName = esbVO.getServiceName();
        ApiResult apiResult = null;
        if (serviceName.equals(Constant.APP_LITTLE_ORDER)) {
            //小订订单
            apiResult = saveAppLittleOrder(esbVO);
        } else if (serviceName.equals(Constant.APP_TSET_DRIVE)) {
            //试驾留资
            apiResult = saveTsetDrive(esbVO);
        } else if (serviceName.equals(Constant.APP_REGIONAL_MANAGER)) {
            //获取大区经理信息
            apiResult = getRegionalManager(esbVO);
        } else if (serviceName.equals(Constant.APP_ORDER_UNSUBSCRIBE)) {
            //订单退订
            apiResult = saveAppOrderUnsubscribe(esbVO);
        }else if (serviceName.equals(Constant.APP_CREDIT_INVESTIGATION)) {
            //进件
            apiResult = saveAppCreditInvestigation(esbVO);
        }else if (serviceName.equals(Constant.APP_PATCH_BOLT)) {
            //补件
            apiResult = saveAppPatchBolt(esbVO);
        }else if (serviceName.equals(Constant.APP_PMS_FINANCE_SUB)) {
            //金融方案提交
            apiResult = financeSubmit(esbVO);
        }else if (serviceName.equals(Constant.APP_PMS_FINANCE_CONFIRM)) {
            //金融方案用户确认结果返回
            apiResult = financeConfirm(esbVO);
        } else {
            return ResponseUtil.fail(500, "没有对应的业务接口!");
        }
        return apiResult;
    }

    private ApiResult saveAppPatchBolt(EsbVO esbVO) {
        ApiResult apiResult = null;
        String reqBody = esbVO.getReqBody();
        PatchBoltVO patchBoltVO = JSONObject.toJavaObject(JSON.parseObject(reqBody), PatchBoltVO.class);
        EaiLog eaiLog = new EaiLog();
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("APP传递征信补件信息给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            //调用内部接口
            apiResult=ResponseUtil.ok();
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return apiResult;
    }

    private ApiResult saveAppCreditInvestigation(EsbVO esbVO) {
        ApiResult apiResult = null;
        String reqBody = esbVO.getReqBody();
        CustomerCreditAppVO customerCreditAppVO = JSONObject.toJavaObject(JSON.parseObject(reqBody), CustomerCreditAppVO.class);
        EaiLog eaiLog = new EaiLog();
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("APP传递征信进件信息给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            //调用内部接口
          /*  CustomerCreditAppVO customerCreditAppVO=new CustomerCreditAppVO();
            BeanUtils.copyProperties(creditInvestigationVO,customerCreditAppVO);*/
            apiResult= appCustomerCredit2PMSImpl.AppCustomerCredit2PMS(customerCreditAppVO);
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return apiResult;
    }

    private ApiResult saveAppOrderUnsubscribe(EsbVO esbVO) {
        ApiResult apiResult = null;
        String reqBody = esbVO.getReqBody();
        OrderUnsubscribeVO orderUnsubscribeVO = JSONObject.toJavaObject(JSON.parseObject(reqBody), OrderUnsubscribeVO.class);
        EaiLog eaiLog = new EaiLog();
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("APP传递订单退订状态给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            //调用内部接口
            CancelVOAPP cancelVOAPP = new CancelVOAPP();
            cancelVOAPP.setComment(orderUnsubscribeVO.getComment());
            cancelVOAPP.setUserId(String.valueOf(orderUnsubscribeVO.getUserId()));
            cancelVOAPP.setOrderNo(orderUnsubscribeVO.getOrderNo());
            cancelVOAPP.setRefundOrderNo(orderUnsubscribeVO.getRefundOrderNo());
            cancelVOAPP.setRefundStatus(orderUnsubscribeVO.getRefundStatus());
            apiResult = app2PmsImpl.cancelApplyApp(cancelVOAPP);
            if (apiResult==null){
                apiResult=ResponseUtil.ok();
            }
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return apiResult;
    }

    private ApiResult getRegionalManager(EsbVO esbVO) {
        ApiResult apiResult = null;
        String reqBody = esbVO.getReqBody();
        RegionalManagerVO regionalManagerVO = JSONObject.toJavaObject(JSON.parseObject(reqBody), RegionalManagerVO.class);
        EaiLog eaiLog = new EaiLog();
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("系统获取大区经理信息");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            //调用内部接口
            RegionManagerReqVO regionManagerReqVO = new RegionManagerReqVO();
            BeanUtils.copyProperties(regionalManagerVO, regionManagerReqVO);
            List<RegionManagerVO> regionManagerVOS = app2BaseDataServiceImpl.listRegionManager(regionManagerReqVO);
            apiResult = ResponseUtil.ok(regionManagerVOS);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            eaiLog.setDisposeStatus(2);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return apiResult;
    }

    private ApiResult saveTsetDrive(EsbVO esbVO) {
        ApiResult apiResult = null;
        String reqBody = esbVO.getReqBody();
        TestDriveVO testDriveVO = JSONObject.toJavaObject(JSON.parseObject(reqBody), TestDriveVO.class);
        EaiLog eaiLog = new EaiLog();
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("EAI系统发送试乘试驾信息给PMS系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            //调用内部接口
            CustomerTestDriveVO customerTestDriveVO=new CustomerTestDriveVO();
            BeanUtils.copyProperties(testDriveVO,customerTestDriveVO);
            apiResult = newCustomerClueServiceImpl.newCustomerTestDrive(customerTestDriveVO);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail();
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return apiResult;
    }

    private ApiResult saveAppLittleOrder(EsbVO esbVO) {
        ApiResult apiResult = null;
        String reqBody = esbVO.getReqBody();
        AppLittleOrderVO appLittleOrderVO = JSONObject.toJavaObject(JSON.parseObject(reqBody), AppLittleOrderVO.class);
        EaiLog eaiLog = new EaiLog();
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("EAI系统发送小订订单给PMS系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            //调用内部接口
            OrderCustomerVO orderCustomerVO = dozerMapper.map(appLittleOrderVO, OrderCustomerVO.class);
            if (!appLittleOrderVO.getOrderStatus().equals("")) {
                orderCustomerVO.setOrderStatus(Integer.parseInt(appLittleOrderVO.getOrderStatus()));
            }
            if (!appLittleOrderVO.getCertType().equals("")) {
                orderCustomerVO.setCertType(Integer.parseInt(appLittleOrderVO.getCertType()));
            }
            if (!appLittleOrderVO.getTotalAmount().equals("")) {
                orderCustomerVO.setTotalAmount(new BigDecimal(appLittleOrderVO.getTotalAmount()));
            }
            if (!appLittleOrderVO.getOrderAmount().equals("")) {
                orderCustomerVO.setOrderAmount(new BigDecimal(appLittleOrderVO.getOrderAmount()));
            }
            if (!appLittleOrderVO.getStateSubsidy().equals("")) {
                orderCustomerVO.setStateSubsidy(new BigDecimal(appLittleOrderVO.getStateSubsidy()));
            }
            if (!appLittleOrderVO.getLocalSubsidy().equals("")) {
                orderCustomerVO.setLocalSubsidy(new BigDecimal(appLittleOrderVO.getLocalSubsidy()));
            }
            if (!appLittleOrderVO.getBlAmount().equals("")) {
                orderCustomerVO.setBlAmount(new BigDecimal(appLittleOrderVO.getBlAmount()));
            }

            if (!appLittleOrderVO.getBfAmount().equals("")) {
                orderCustomerVO.setBfAmount(new BigDecimal(appLittleOrderVO.getBfAmount()));
            }
            if (!appLittleOrderVO.getVehicleStatus().equals("")) {
                orderCustomerVO.setVehicleStatus(Integer.parseInt(appLittleOrderVO.getVehicleStatus()));
            }
            ApiResult checkApiResult = produceModelCheckDubboServiceImpl.check(appLittleOrderVO.getProductTypeCode(), appLittleOrderVO.getInteriorCode(), appLittleOrderVO.getColorCode(), appLittleOrderVO.getFeatureCode());
            eaiLog.setResponseReceiveTime(new Date());
            if (checkApiResult.getCode() == 200) {
                apiResult = app2PmsImpl.receiveApp(orderCustomerVO);
                eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
                if (apiResult.getCode() == -1) {
                    eaiLog.setDisposeStatus(2);
                }
                Map map = new HashMap();
                map.put("order_no", orderCustomerVO.getOrderNo());
                apiResult.setData(map);
            }else {
                eaiLog.setDisposeStatus(3);
                eaiLog.setPmsResultContent(JSONObject.toJSONString(checkApiResult));
                apiResult = checkApiResult;
//                apiResult.setData("车型选装内外饰校验不通过!");
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //  SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return apiResult;
    }

    /**
     * 金融方案提交app->pms
     * @param esbVO
     * @return
     */
    private ApiResult financeSubmit(EsbVO esbVO) {
        ApiResult apiResult = null;
        String reqBody = esbVO.getReqBody();
        CustomerCreditFinancialPlanVO customerCreditFinancialPlanVO = JSONObject.toJavaObject(JSON.parseObject(reqBody), CustomerCreditFinancialPlanVO.class);
        EaiLog eaiLog = new EaiLog();
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("APP系统发送金融方案提交给PMS系统");
        eaiLog.setSourceSystem(Constant.APP);
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            apiResult = appCustomerCredit2PMSImpl.AppCreditFinancialPlan2PMS(customerCreditFinancialPlanVO);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
//                apiResult = ResponseUtil.fail();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return apiResult;
    }

    /**
     * 金融方案用户确认结果返回app->pms
     * @param esbVO
     * @return
     */
    private ApiResult financeConfirm(EsbVO esbVO) {
        ApiResult apiResult = null;
        String reqBody = esbVO.getReqBody();
       CustomerCreditResultVO customerCreditResultVO = JSONObject.toJavaObject(JSON.parseObject(reqBody), CustomerCreditResultVO.class);
        EaiLog eaiLog = new EaiLog();
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("APP系统发送金融方案用户确认结果给PMS系统");
        eaiLog.setSourceSystem(Constant.APP);
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            apiResult = appCustomerCredit2PMSImpl.AppCustomerConfirmCredit2PMS(customerCreditResultVO);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
//                apiResult = ResponseUtil.fail();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return apiResult;
    }
}
